const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Contrast = require('../model/contrast.model')
const ContrastBucketSchemaConfig = {
  versionKey: false
}

const ContrastBucketSchema = new Schema({
  contrast: { type: Schema.Types.ObjectId, ref: 'Contrast', required: true },
  user: { type: Schema.Types.ObjectId, ref: 'User' },
  data: [Number]
}, ContrastBucketSchemaConfig)

ContrastBucketSchema.post('save', function(doc) {
  Contrast.findById(doc.contrast, function(err, contrast) {
    if (err) return console.log(err)
    const scorePoint = _calScorePoint(contrast.subjects, doc.data)
    contrast.averages.push({ bucket: doc.id, point: scorePoint })
    // contrast.save(function(err, newContrast) {
    //   if (err) {
    //     console.log('[ERROR]save a contrast bucket in contrast model failed')
    //     return new Error(err.message)
    //   }
    //   console.log(newContrast.averages)
    //   console.log('calculate score point successfully')
    // })
    contrast.save()
  })
})

/**
 * 计算绩点
 * @param subjects 科目集
 * @param scores 成绩集
 * @private
 */
function _calScorePoint(subjects, scores) {
  let sum = 0
  let totalCredit = 0
  for (let i = 0; i < scores.length; i++) {
    sum += _split50(scores[i]) * subjects[i].weight
    totalCredit += subjects[i].weight
  }
  const result = sum / (totalCredit * 10)
  return result.toFixed(2)
}

function _split50(mark) {
  if (mark < 0) return 0
  if (mark > 100) return 50
  return mark - 50
}

exports = module.exports = ContrastBucketSchema
